package security.channel;

import java.io.FileReader;
import java.io.IOException;
import java.net.Socket;

import java.security.InvalidKeyException;
import java.security.PublicKey;
import java.security.PrivateKey;

import javax.crypto.Cipher;

import org.bouncycastle.openssl.PEMReader;

/**
 * This class represents a channel over a network thats messages are encrypted
 * or decrpyted by using any RSA algorithm.
 */
public class RSAChannel extends SecureChannel {
	
	//used algorithm for encryption and decryption
	public static final String algorithm = "RSA/NONE/OAEPWithSHA256AndMGF1Padding";

	public RSAChannel(Socket socket, String pathToPublicKey,
			PrivateKey privateKey) throws IOException {
		super(socket);

		// get public key
		PublicKey publicKey = null;
		if (!pathToPublicKey.isEmpty()) {
			PEMReader pemIn = new PEMReader(new FileReader(pathToPublicKey));
			publicKey = (PublicKey) pemIn.readObject();
		}

		// initialize cipher with specified algorithm
		createCipher(algorithm);
		
		// initialize cipher to en- and decrypt
		try { 
			if(publicKey != null)
				this.encrypt.init(Cipher.ENCRYPT_MODE, publicKey);
			if(privateKey != null)
				this.decrypt.init(Cipher.DECRYPT_MODE, privateKey);
		} catch (InvalidKeyException e) {
			System.err.println("ERROR: init cipher to en- or decrpyt in "
					+ this.getClass() + ", invalidkeyexception: "
					+ e.getMessage());
		}
	}
}